const editOrAddStudentModal = document.querySelector("#edit-or-add-student-modal");
const addScoreModal = document.querySelector("#add-score-modal");
const addScoreBeachModal = document.querySelector("#add-score-beach-modal");
// 当 show 实例方法被调用之后，此事件被立即触发。
editOrAddStudentModal.addEventListener("show.bs.modal", () => {

})
// 当调用 hide 实例方法时触发。（模态框开始隐藏时触发）
// 重置表单数据
editOrAddStudentModal.addEventListener("hide.bs.modal", () => {
    const idInput = document.querySelector("#edit-input-id");
    const nameInput = document.querySelector("#edit-input-name");
    const genderInput = document.querySelector(`input[type='radio']`);
    const ageInput = document.querySelector("#edit-input-age");
    const markInput = document.querySelector("#edit-input-mark");
    idInput.value = -1;
    nameInput.value = '';
    genderInput.checked = true;
    ageInput.value = null;
    markInput.value = null;
})

addScoreModal.addEventListener("show.bs.modal", () => {
    document.querySelector("#student-score").value = null;
})

addScoreBeachModal.addEventListener("show.bs.modal", () => {
    document.querySelector("#score-data").value = null;
})


const editOrAddStudentModalClose = document.querySelector("#edit-or-add-student-modal-close");


// 删除学生
function deleteStudent(id) {
    if (confirm(`确定删除 id 为${id} 的学生信息吗`)) {
        // 指定后端API的URL
        const apiUrl = `/hand/delete/${id}`;
        // 使用fetch发送请求
        fetch(apiUrl, {
            method: "DELETE"
        }).then(response => {
            // 检查HTTP响应状态
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            // 解析JSON响应
            return response.json();
        }).then(data => {
            // 在这里处理从后端获取的数据
            console.log(data);
            if (data.code === 200) {
                zjAlert.success("删除成功！", () => {
                    location.reload();
                })
            }
        }).catch(error => {
            // 处理请求或响应错误
            console.error('发生错误:', error);
        });
    }
}

/**
 * 打开弹出框
 * @param opType 操作类型/添加或修改
 * @param student 学生实体
 */
function openDialog(opType, student) {
    console.log(student)
    const idInput = document.querySelector("#edit-input-id");
    const nameInput = document.querySelector("#edit-input-name");
    const genderInput = document.querySelector(`input[type='radio'][value='${student ? student["gender"] : 1}']`);
    const ageInput = document.querySelector("#edit-input-age");
    const markInput = document.querySelector("#edit-input-mark");
    if (student) {
        idInput.value = student['id'];
        nameInput.value = student['name'];
        genderInput.checked = true;
        ageInput.value = student["age"];
        markInput.value = student['mark'];
    }
}

/**
 * 获取被选中的单选框
 * @param selector 单选框选择器
 * @returns {*}
 */
function queryCheckedRadio(selector) {
    const nodeListOf = document.querySelectorAll(selector);
    for (let i = 0; i < nodeListOf.length; i++) {
        if (nodeListOf[i].checked === true) {
            return nodeListOf[i];
        }
    }
}

function dialogConfirm() {
    const idInput = document.querySelector('#edit-input-id');
    console.log(idInput)
    console.log(idInput.value)
    const opType = idInput.value === "0" ? 'add' : 'update';
    console.log("==========", opType);
    switch (opType) {
        case "update":
            updateStudent();
            break;
        case "add":
            addStudent();
            break;
        case "addBeach":
            addStudentBeach();
            break;
    }
}

function updateStudent() {
    const idInput = document.querySelector("#edit-input-id");
    const nameInput = document.querySelector("#edit-input-name");
    const genderInput = queryCheckedRadio(`input[type='radio'][name='edit-input-gender']`);
    const ageInput = document.querySelector("#edit-input-age");
    const markInput = document.querySelector("#edit-input-mark");
    console.log(genderInput.value);
    const param = {
        id: idInput.value, name: nameInput.value, gender: genderInput.value, age: ageInput.value, mark: markInput.value
    }
    const apiUrl = "/hand/update";
    fetch(apiUrl, {
        method: "PUT", headers: {
            'Content-Type': 'application/json', // 指定请求的数据类型为JSON
        }, body: JSON.stringify(param)
    }).then(response => {
        // 检查HTTP响应状态
        if (!response.ok) {
            throw new Error('网络请求失败');
        }
        // 解析JSON响应
        return response.json();
    }).then(data => {
        // 在这里处理从后端获取的数据
        console.log(data, data.data);
        if (data.code === 200) {
            editOrAddStudentModalClose.click();
            zjAlert.success("修改成功！", () => {
                location.reload();
            });
        }
    }).catch(error => {
        // 处理请求或响应错误
        console.error('发生错误:', error);
    });
}

/**
 * 添加学生
 */
function addStudent() {
    const nameInput = document.querySelector("#edit-input-name");
    const genderInput = queryCheckedRadio(`input[type='radio'][name='edit-input-gender']`);
    const ageInput = document.querySelector("#edit-input-age");
    const markInput = document.querySelector("#edit-input-mark");

    const param = {
        name: nameInput.value,
        gender: genderInput.value,
        age: ageInput.value,
        mark: markInput.value
    }
    if (allNotNull(param.name, param.gender, param.age)) {
        const apiUrl = "/hand/student/add";
        fetch(apiUrl, {
            method: "POST", headers: {
                'Content-Type': 'application/json', // 指定请求的数据类型为JSON
            }, body: JSON.stringify(param)
        }).then(response => {
            // 检查HTTP响应状态
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            // 解析JSON响应
            return response.json();
        }).then(data => {
            // 在这里处理从后端获取的数据
            console.log(data, data.data);
            if (data.code === 200) {
                editOrAddStudentModalClose.click();
                zjAlert.success("添加成功！", () => {
                    location.reload();
                })
            }
        }).catch(error => {
            // 处理请求或响应错误
            console.error('发生错误:', error);
            zjAlert.danger("发生错误！");
        });
    } else {
        zjAlert.danger("请填写所有参数！");
    }
}

/**
 * 批量添加学生
 */
function addStudentBeach() {

}

/**
 * 渲染学生信息表格
 * @param students 每一项为学生对象的数组
 */
function renderStudentList(students) {
    const resultTable = document.querySelector("#student-list-table>tbody");
    students.forEach(student => {
        const tr = document.createElement("tr");
        const tdId = document.createElement("td");
        const tdName = document.createElement("td");
        const tdGender = document.createElement("td");
        const tdAge = document.createElement("td");
        const tdMark = document.createElement("td");
        tdId.textContent = student['id'];
        tdName.textContent = student['name'];
        tdGender.textContent = student['gender'] === 1 ? '男' : '女';
        tdAge.textContent = student['age'];
        tdMark.textContent = student['mark'];
        tr.appendChild(tdId);
        tr.appendChild(tdName);
        tr.appendChild(tdGender);
        tr.appendChild(tdAge);
        tr.appendChild(tdMark);
        tr.insertAdjacentHTML("beforeend", `<td>
            <button type="button" class="btn btn-danger btn-sm" onclick="deleteStudent(${student['id']})">删除</button>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#edit-or-add-student-modal" onclick='openDialog("update",${JSON.stringify(student)})'>编辑</button>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#score-table-modal" onclick='getScore(${student["id"]})'>成绩</button>
        </td>`)
        resultTable.appendChild(tr);
    })
}

// 搜索学生
function searchStudent() {
    const resultTable = document.querySelector("#student-list-table>tbody");
    resultTable.innerHTML = '';
    const searchName = document.querySelector("#search-input-name");
    const apiUrl = `/hand/search${searchName.value ? '/' + searchName.value : ''}`;
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        }).then(data => {
        if (data.code === 200) {
            console.log(data)
            renderStudentList(data.data);
        }
    }).catch(error => {
        console.log(error)
    })
}

/**
 * 判断是否所有给定参数都不为空
 * @param tokens 给定参数列表
 * @returns {boolean}
 */
function allNotNull(...tokens) {
    for (let i = 0; i < tokens.length; i++) {
        // 0 是有意义的数字
        if (!tokens[i] && tokens[i] !== 0) return false;
    }
    return true;
}

// 添加成绩
function addScore() {
    const studentId = document.querySelector("#student-dropdown").value;
    const courseId = document.querySelector("#course-dropdown").value;
    const score = document.querySelector("#student-score").value;
    console.log(studentId, courseId, score);
    console.log("=========", score);
    if (allNotNull(studentId, courseId, score)) {
        const apiUrl = '/hand/student/add-score';
        const param = {
            studentId, courseId, score
        }
        fetch(apiUrl, {
            method: "POST", headers: {
                'Content-Type': 'application/json', // 指定请求的数据类型为JSON
            }, body: JSON.stringify(param)
        }).then(response => {
            // 检查HTTP响应状态
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            // 解析JSON响应
            return response.json();
        }).then(data => {
            // 在这里处理从后端获取的数据
            console.log(data, data.data);
            if (data.code === 200) {
                zjAlert.success("添加成功！");
            }
        }).catch(error => {
            // 处理请求或响应错误
            console.error('发生错误:', error);
        });
    } else {
        zjAlert.warning("请填写所有字段！")
    }
}

// 批量添加成绩
function addScoreBeach() {
    const scoreData = document.querySelector("#score-data");
    try {
        const jsonData = JSON.parse(scoreData.value);
        if (Array.isArray(jsonData)) {
            const apiUrl = `/hand/student/add-score-beach`
            fetch(apiUrl, {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json', // 指定请求的数据类型为JSON
                }, // [{"studentId":1,"courseId":2,"score":90},{"studentId":2,"courseId":2,"score":90}]
                body: scoreData.value
            }).then(response => {
                // 检查HTTP响应状态
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                // 解析JSON响应
                return response.json();
            }).then(data => {
                // 在这里处理从后端获取的数据
                console.log(data, data.data);
                if (data.code === 200) {
                    zjAlert.success("添加成功！");
                }
            }).catch(error => {
                // 处理请求或响应错误
                console.error('发生错误:', error);
            });
        }
    } catch (e) {
        console.log("发生错误！", e)
    }
}

// 渲染学生下拉框
function renderStudentDropdown(students) {
    const dropdown = document.querySelector("#student-dropdown");
    dropdown.innerHTML = '';
    students.forEach(student => {
        const item = document.createElement("option");
        item.value = student['id'];
        item.textContent = student['name'];
        dropdown.appendChild(item);
    });
}

// 渲染课程下拉框
function renderCourseDropdown(courses) {
    const dropdown = document.querySelector("#course-dropdown");
    dropdown.innerHTML = '';
    courses.forEach(course => {
        const item = document.createElement("option");
        item.value = course['id'];
        item.textContent = course['courseName'];
        dropdown.appendChild(item);
    });
}

// 渲染学生成绩表格
function renderScoreTable(studentVo) {
    const table = document.querySelector("#student-score-table");
    table.querySelector("caption").innerHTML = `${studentVo['name']} 同学的成绩单`
    const tbody = table.querySelector("tbody");
    tbody.innerHTML = '';
    if (studentVo['courses'].length === 0) {
        tbody.innerHTML = `<h1>暂无数据</h1>`;
    } else {
        studentVo['courses'].forEach(course => {
            const tr = document.createElement("tr");
            const td1 = document.createElement("td");
            const td2 = document.createElement("td");
            td1.textContent = course['courseName'];
            td2.textContent = course['score'];
            tr.appendChild(td1);
            tr.appendChild(td2);
            tbody.appendChild(tr);
        })
    }
}

// 获取学生成绩表
function getScore(studentId) {
    if (allNotNull(studentId)) {
        const apiUrl = `/hand/score-table/${studentId}`
        fetch(apiUrl).then(res => {
            if (!res.ok)
                throw new Error("网络请求失败！");
            return res.json();
        }).then(data => {
            if (data.code === 200) {
                console.log(data.data)
                renderScoreTable(data.data);
            }
        }).catch(err => {
            console.log("发生错误:", err);
        })
    }
}

const zjAlert = {
    success: (message, callback) => {
        alertMessage("success", message, callback)
    },
    info: (message, callback) => {
        alertMessage("info", message, callback)
    },
    warning: (message, callback) => {
        alertMessage("warning", message, callback)
    },
    danger: (message, callback) => {
        alertMessage("danger", message, callback)
    },
    primary: (message, callback) => {
        alertMessage("primary", message, callback)
    },
    secondary: (message, callback) => {
        alertMessage("secondary", message, callback)
    },
    dark: (message, callback) => {
        alertMessage("dark", message, callback)
    },
    light: (message, callback) => {
        alertMessage("light", message, callback)
    }
}

// 弹出框
function alertMessage(type, message, callback) {
    const alertType = {
        success: "成功！",
        info: "信息！",
        warning: "警告！",
        danger: "错误！",
        primary: "首选！",
        secondary: "次要！",
        dark: "",
        light: ""
    }
    const alertBox = document.querySelector("#alert-box");
    alertBox.className = '';
    alertBox.classList.add("alert", `alert-${type}`);
    alertBox.querySelector("strong").textContent = alertType[type];
    alertBox.querySelector("span").textContent = message;
    anime({
        targets: alertBox,
        height: 50,
        paddingTop: 5,
        paddingBottom: 5,
        duration: 200,
        easing: 'easeOutQuad'
    })
    setTimeout(() => {
        anime({
            targets: alertBox,
            height: 0,
            paddingTop: 0,
            paddingBottom: 0,
            duration: 200,
            easing: 'easeOutQuad',
            complete: () => {
                if (callback)
                    callback();
            }
        })
    }, 2000);
}

// 初始化学生
function initStudent() {
    const apiUrl = '/hand/student/all'
    fetch(apiUrl).then(response => {
        // 检查HTTP响应状态
        if (!response.ok) {
            throw new Error('网络请求失败');
        }
        // 解析JSON响应
        return response.json();
    }).then(data => {
        // 在这里处理从后端获取的数据
        console.log(data);
        if (data.code === 200) {
            localStorage.setItem("students", JSON.stringify(data.data))
            renderStudentDropdown(data.data);
            renderStudentList(data.data);
        }
    }).catch(error => {
        // 处理请求或响应错误
        console.error('发生错误:', error);
    });
}

// 初始化课程
function initCourse() {
    const apiUrl = '/hand/course/all';
    fetch(apiUrl).then(response => {
        // 检查HTTP响应状态
        if (!response.ok) {
            throw new Error('网络请求失败');
        }
        // 解析JSON响应
        return response.json();
    }).then(data => {
        // 在这里处理从后端获取的数据
        console.log(data);
        if (data.code === 200) {
            renderCourseDropdown(data.data);
        }
    }).catch(error => {
        // 处理请求或响应错误
        console.error('发生错误:', error);
    });
}

function init() {
    initStudent();
    initCourse();
}

// 初始化
init();

